<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Other Request Bodies</title>
</head>

<body>
<h1>Other Request Bodies</h1>

<p>The previous example demonstrated how to accept the payload of
a <code>POST</code> carrying HTML form data.  What about <code>POST</code>
requests with data in some other format?  Or even <code>PUT</code> requests?
Here is an example which demonstrates how to get <em>any</em> request body,
regardless of its format - using the request's
 <code class="API" base="twisted.web.iweb.IRequest">content</code> attribute.</p>

<p>The only significant difference between this example and the previous is that
instead of accessing <code class="python">request.args</code>
in <code class="python">render_POST</code>, it
uses <code class="python">request.content</code> to get the request's body
directly:</p>

<pre class="python">
...
    def render_POST(self, request):
        return '&lt;html&gt;&lt;body&gt;You submitted: %s&lt;/body&gt;&lt;/html&gt;' % (cgi.escape(request.content.read()),)
</pre>

<p><code class="python">request.content</code> is a file-like object, so the
body is read from it.  The exact type may vary, so avoid relying on non-file
methods you may find (such as <code class="python">getvalue</code> when happens
to be a <code class="python">StringIO</code> instance).</p>

<p>Here's the complete source for this example - again, almost identical to the
previous <code>POST</code> example, with
only <code class="python">render_POST</code> changed:</p>

<pre class="python">
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor

import cgi

class FormPage(Resource):
    def render_GET(self, request):
        return '&lt;html&gt;&lt;body&gt;&lt;form method="POST"&gt;&lt;input name="the-field" type="text" /&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;'

    def render_POST(self, request):
        return '&lt;html&gt;&lt;body&gt;You submitted: %s&lt;/body&gt;&lt;/html&gt;' % (cgi.escape(request.content.read()),)

root = Resource()
root.putChild("form", FormPage())
factory = Site(root)
reactor.listenTCP(8880, factory)
reactor.run()
</pre>

</body>
</html>
